package com.ruoyi.system.controller;

import java.beans.Transient;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import static com.ruoyi.common.utils.uuid.Seq.getId;

/**
 * 领用单主Controller
 *
 * @author ruoyi
 * @date 2024-10-31
 */
@RestController
@RequestMapping("/system/HmzBorrowMaster")
public class HmzBorrowMasterController extends BaseController
{
    @Autowired
    private IHmzBorrowMasterService hmzBorrowMasterService;
//    员工操作类
    @Autowired
    private IHmzEmployeeInfoService hmzEmployeeInfoService;
//    领用单子表操作类
    @Autowired
    private IHmzBorrowDetailService hmzBorrowDetailService;
//    托盘操作类
    @Autowired
    private IHmzItemService hmzItemService;
    @Autowired
    private IHmzMoneyInfoService hmzMoneyInfoService;

    /**
     * 查询领用单主列表
     */
    @PreAuthorize("@ss.hasPermi('system:HmzBorrowMaster:list')")
    @GetMapping("/list")
    public TableDataInfo list(HmzBorrowMaster hmzBorrowMaster) {
        String itemRfidCode = hmzBorrowMaster.getItemRfidCode();
        if (itemRfidCode != null && !"".equals(itemRfidCode)) {
            List<Integer> integers = hmzBorrowDetailService.selectHmzBorrowDetailByRfidCode(itemRfidCode);
            if(integers.size()!=0){
                hmzBorrowMaster.setIds(integers);
            }
            startPage();
//        如果条件查询中有员工名称，则先取出员工id
            System.out.printf("员工名称=" + hmzBorrowMaster.getName());
            if (hmzBorrowMaster.getName() != null) {
                HmzEmployeeInfo hmzEmployeeInfo = hmzEmployeeInfoService.selectHmzEmployeeInfoByName(hmzBorrowMaster.getName());
                if (hmzEmployeeInfo == null) {
                    return getDataTable(Collections.emptyList());
                }
                Long id = hmzEmployeeInfo.getId();
                hmzBorrowMaster.setEmployeeId(id);
                System.out.printf("员工id=" + id);
            }
            List<HmzBorrowMaster> list = hmzBorrowMasterService.selectHmzBorrowMasterList(hmzBorrowMaster);
            List<HmzBorrowMaster> DataList = new ArrayList<>();
//            获取员工id进行遍历查询,获取到员工详情
            for (HmzBorrowMaster item : list) {
                int ghQuantity = 0;
                HmzEmployeeInfo hmzEmployeeInfo = hmzEmployeeInfoService.selectHmzEmployeeInfoById(item.getEmployeeId());
//           给领用单主表实体类的临时字段赋值(名称和rfid编号)
                if (hmzEmployeeInfo != null) {
                    item.setName(hmzEmployeeInfo.getName());
                    item.setRfidCode(hmzEmployeeInfo.getRfidCode());
                }
////            遍历领用单详情,根据查询的托盘编号查询出零用过此托盘的所有领用单
//            if (hmzBorrowMaster.getItemRfidCode()!=null&&!"".equals(hmzBorrowMaster.getItemRfidCode())){
////        获取领用单详情
//                HmzBorrowDetail hmzBorrowDetail =new HmzBorrowDetail();
//                hmzBorrowDetail.setMasterId(item.getId());
//                List<HmzBorrowDetail> hmzBorrowDetails =  hmzBorrowDetailService.selectHmzBorrowDetailList(hmzBorrowDetail);
//                for (HmzBorrowDetail res : hmzBorrowDetails) {
//                    String rfidCode = res.getRfidCode();
//                    if (hmzBorrowMaster.getItemRfidCode().equals(rfidCode)) {
//                        DataList.add(item);
//                    }
//                }
//
//
//            }


////            查询领用单详情
//            HmzBorrowDetail hmzBorrowDetail = new HmzBorrowDetail();
//            hmzBorrowDetail.setMasterId(item.getId());
//          List<HmzBorrowDetail> hmzBorrowDetails =  hmzBorrowDetailService.selectHmzBorrowDetailList(hmzBorrowDetail);

////           遍历领用单详情
//            if(hmzBorrowDetails!=null){
//                for (HmzBorrowDetail res : hmzBorrowDetails){
//                    HmzItem hmzItem = hmzItemService.selectHmzItemByRfidCode(res.getRfidCode());
////              如果查询的托盘是在库的，说明归还了，归还数量+1
//                    if (hmzItem.getGoodsState()==0L){
//                        System.out.printf("托盘状态="+hmzItem.getGoodsState());
//                        ghQuantity++;
//                        System.out.printf("归还数量="+ghQuantity);
//                    }
//                    item.setGhQuantity((long) ghQuantity);
//                }
//            }

            }

//            if (hmzBorrowMaster.getItemRfidCode() != null && !"".equals(hmzBorrowMaster.getItemRfidCode())) {
//                return getDataTable(DataList);
//            }
            System.out.println("item = " + list);
            return getDataTable(list);
        }
        else {
        startPage();
//        如果条件查询中有员工名称，则先取出员工id
        System.out.printf("员工名称=" + hmzBorrowMaster.getName());
        if (hmzBorrowMaster.getName() != null) {
            HmzEmployeeInfo hmzEmployeeInfo = hmzEmployeeInfoService.selectHmzEmployeeInfoByName(hmzBorrowMaster.getName());
            if (hmzEmployeeInfo == null) {
                return getDataTable(Collections.emptyList());
            }
            Long id = hmzEmployeeInfo.getId();
            hmzBorrowMaster.setEmployeeId(id);
            System.out.printf("员工id=" + id);
        }
        List<HmzBorrowMaster> list = hmzBorrowMasterService.selectHmzBorrowMasterList(hmzBorrowMaster);
        List<HmzBorrowMaster> DataList = new ArrayList<>();
//            获取员工id进行遍历查询,获取到员工详情
        for (HmzBorrowMaster item : list) {
            int ghQuantity = 0;
            HmzEmployeeInfo hmzEmployeeInfo = hmzEmployeeInfoService.selectHmzEmployeeInfoById(item.getEmployeeId());
//           给领用单主表实体类的临时字段赋值(名称和rfid编号)
            if (hmzEmployeeInfo != null) {
                item.setName(hmzEmployeeInfo.getName());
                item.setRfidCode(hmzEmployeeInfo.getRfidCode());
            }
        }
        if (hmzBorrowMaster.getItemRfidCode() != null && !"".equals(hmzBorrowMaster.getItemRfidCode())) {
            return getDataTable(DataList);
        }
        System.out.println("item = " + list);
        return getDataTable(list);
    }
    }

    /**
     * 导出领用单主列表
     */
    @PreAuthorize("@ss.hasPermi('system:HmzBorrowMaster:export')")
    @Log(title = "领用单主", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, HmzBorrowMaster hmzBorrowMaster)
    {
        List<HmzBorrowMaster> list = hmzBorrowMasterService.selectHmzBorrowMasterList(hmzBorrowMaster);
        ExcelUtil<HmzBorrowMaster> util = new ExcelUtil<HmzBorrowMaster>(HmzBorrowMaster.class);
        util.exportExcel(response, list, "领用单主数据");
    }

    /**
     * 获取领用单主详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:HmzBorrowMaster:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {

//        获取领用单详情
        HmzBorrowMaster HmzBorrowMaster = hmzBorrowMasterService.selectHmzBorrowMasterById(id);
        //        获取员工详情
        HmzEmployeeInfo hmzEmployeeInfo = hmzEmployeeInfoService.selectHmzEmployeeInfoById(HmzBorrowMaster.getEmployeeId());
//        给详情赋值员工的rfidcode和名称
        HmzBorrowMaster.setName(hmzEmployeeInfo.getName());
        HmzBorrowMaster.setRfidCode(hmzEmployeeInfo.getRfidCode());

        return success(HmzBorrowMaster);
    }

    /**
     * 新增领用单主
     */
    @PreAuthorize("@ss.hasPermi('system:HmzBorrowMaster:add')")
    @Log(title = "领用单主", businessType = BusinessType.INSERT)
    @PostMapping
//    添加事务注解，插入出错回滚
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult add (@RequestBody HmzBorrowMaster hmzBorrowMaster )
    {
        Long employeeId = hmzBorrowMaster.getEmployeeId();
        if (employeeId == null) {
            return error("人员不能为空");
        }
        HmzEmployeeInfo hmzEmployeeInfo = hmzEmployeeInfoService.selectHmzEmployeeInfoById(employeeId);
        if(hmzEmployeeInfo !=null){
            if(hmzEmployeeInfo.getIsLoss()==1){
                return error("当前用户已挂失");
            }
        }
        List<HmzBorrowDetail> hmzBorrowDetailListnew=new ArrayList<>();
        List<HmzBorrowDetail> hmzBorrowDetail = hmzBorrowMaster.getHmzBorrowDetail();
        if(hmzBorrowDetail !=null){
            for (HmzBorrowDetail borrowDetail : hmzBorrowDetail) {
                HmzItem hmzItem = hmzItemService.selectHmzItemByRfidCode(borrowDetail.getRfidCode());
                if(hmzItem !=null && hmzItem.getGoodsState()==0){
                    hmzBorrowDetailListnew.add(borrowDetail);
                }
            }
        }else {
            return error("操作失败");
        }
        hmzBorrowMaster.setHmzBorrowDetail(hmzBorrowDetailListnew);
        Long isTow = hmzBorrowMaster.getIsTow();
        if(isTow==0){
            //托盘数量
            int size = hmzBorrowMaster.getHmzBorrowDetail().size();
            BigDecimal bigDecimal = hmzEmployeeInfoService.selectPrice();
            BigDecimal balance = bigDecimal.multiply(new BigDecimal(size));
            if(employeeId !=null){
                int i = hmzEmployeeInfoService.updateBalance(employeeId, balance);
                if(i==0){
                    return error("余额不足");
                }
                HmzMoneyInfo hmzMoneyInfo =new HmzMoneyInfo();
                hmzMoneyInfo.setMoney(balance);
                hmzMoneyInfo.setEmployeeId(employeeId);
                hmzMoneyInfo.setItemNumber((long) size);
                hmzMoneyInfo.setPrice(bigDecimal);
                hmzMoneyInfoService.insertHmzMoneyInfo(hmzMoneyInfo);
            }else {
                return error("人员不能为空");
            }
        }
//        根据日期生成流水号 start
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        Calendar calendar = Calendar.getInstance();
        String datePortion = sdf.format(calendar.getTime());
        System.out.println("生成的序列编号是: " + datePortion); // 输出序列编号
//        根据日期生成流水号 end
        hmzBorrowMaster.setLyNumber(datePortion);
        hmzBorrowMaster.setLyQuantity((long) hmzBorrowMaster.getHmzBorrowDetail().size());
//        插入领用单主表，拿到主表id
        hmzBorrowMasterService.insertHmzBorrowMaster(hmzBorrowMaster);
        Long tableId = hmzBorrowMaster.getId();
       List<HmzBorrowDetail> hmzBorrowDetails = hmzBorrowMaster.getHmzBorrowDetail();
//       检测抛出异常
        HmzItem hmzItem;
        //       遍历将主表id 和 领用明细插入领用子表
        for (HmzBorrowDetail item : hmzBorrowDetails) {
            //        赋值主表id
            item.setMasterId(tableId);
//            根据托盘rfid获取托盘id
            hmzItem = hmzItemService.selectHmzItemByRfidCode(item.getRfidCode());
            if(hmzItem !=null){
//                throw new ServiceException("传入数据错误");
                Long tuoPanId =hmzItem.getId();
                System.out.println("托盘id: " + tuoPanId);
//           赋值托盘id
                item.setItemId(tuoPanId);
                item.setRemark("未归还");



//        插入数据
                hmzBorrowDetailService.insertHmzBorrowDetail(item);
//            更新托盘库存状态
                hmzItem.setGoodsState(1L);
                hmzItem.setEmployeeId(employeeId);
                hmzItemService.updateHmzItem(hmzItem);
            }

        }
        return success("操作成功");
    }

    /**
     * 修改领用单主
     */
    @PreAuthorize("@ss.hasPermi('system:HmzBorrowMaster:edit')")
    @Log(title = "领用单主", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody HmzBorrowMaster hmzBorrowMaster)
    {
        return toAjax(hmzBorrowMasterService.updateHmzBorrowMaster(hmzBorrowMaster));
    }

    /**
     * 删除领用单主
     */
    @PreAuthorize("@ss.hasPermi('system:HmzBorrowMaster:remove')")
    @Log(title = "领用单主", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(hmzBorrowMasterService.deleteHmzBorrowMasterByIds(ids));
    }
}
